package com.semidata.rtd.core.http.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.LastHttpContent;

public class HttpClientHandler extends SimpleChannelInboundHandler<HttpObject> {

    private HttpResponseHandler handler;
    private HttpResponse response;
    private ByteBuf buffer;

    public HttpClientHandler(HttpResponseHandler handler) {
        this.handler = handler;
        this.buffer = Unpooled.buffer();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if (msg instanceof HttpResponse) {
            response = (HttpResponse) msg;
        }
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;

            buffer.writeBytes(content.content());

            if (content instanceof LastHttpContent) {
                if (handler != null)
                    handler.handle(response, buffer);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //cause.printStackTrace();
        ctx.close();
    }

}
